package com.zxjbyte.yiyi.framework.common.core.excel;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 固定表头列宽或者根据内容自适应列宽（根据参数：isAutoWidthByContent）
 *
 * @Author zhangxingjia
 * @Date 2025/3/13 11:11
 * @Version: 1.0
 */
public class DynamicColumnWidthStrategy extends AbstractColumnWidthStyleStrategy {

    private boolean isAutoWidthByContent = false;
    private int fixedWidth = 18;

    private static final int MAX_COLUMN_WIDTH = 255;

    public DynamicColumnWidthStrategy(boolean isAutoWidthByContent, int fixedWidth) {
        if (fixedWidth > MAX_COLUMN_WIDTH) {
            throw new IllegalArgumentException("Fixed column width cannot exceed 255.");
        }
        this.isAutoWidthByContent = isAutoWidthByContent;
        this.fixedWidth = fixedWidth;
    }

    public DynamicColumnWidthStrategy(boolean isAutoWidthByContent) {
        this.isAutoWidthByContent = isAutoWidthByContent;
    }

    public DynamicColumnWidthStrategy() {}

    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        boolean needSetWidth = isHead || !CollUtil.isEmpty(cellDataList);
        if (!needSetWidth) {
            return;
        }
        Sheet sheet = writeSheetHolder.getSheet();
        // isAutoWidthByContent=true 是一个列宽自适应策略。当我们在写入Excel数据时，如果希望根据数据的实际长度来自适应调整列宽， 参考longestMatchColumnWidthStyleStrategy
        if(isAutoWidthByContent){
            Integer columnWidth = dataLength(cellDataList, cell, isHead);
            if (columnWidth < 0) {
                return;
            }
            if (columnWidth > MAX_COLUMN_WIDTH) {
                columnWidth = MAX_COLUMN_WIDTH;
            }
            int maxColumnWidth = sheet.getColumnWidth(cell.getColumnIndex());
            if (columnWidth > maxColumnWidth) {
                writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
            }
        } else {
            int maxColumnWidth = sheet.getColumnWidth(cell.getColumnIndex());
            int width = fixedWidth * 256;
            if (width != maxColumnWidth) {
                writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), width);
            }
        }
    }


    private Integer dataLength(List<WriteCellData<?>> cellDataList, Cell cell, Boolean isHead) {
        if (isHead) {
            return cell.getStringCellValue().getBytes().length;
        }
        WriteCellData<?> cellData = cellDataList.get(0);
        CellDataTypeEnum type = cellData.getType();
        if (type == null) {
            return -1;
        }
        switch (type) {
            case STRING:
                String stringValue = cellData.getStringValue();
                if(stringValue.contains("\n")){
                    String[] lines = stringValue.split("\n");
                    int maxLength = 0;
                    for (String line : lines) {
                        maxLength = Math.max(maxLength, line.getBytes().length);
                    }
                    return maxLength;
                } else {
                    return stringValue.getBytes().length;
                }
            case BOOLEAN:
                return cellData.getBooleanValue().toString().getBytes().length;
            case NUMBER:
                return cellData.getNumberValue().toString().getBytes().length;
            default:
                return -1;
        }
    }
}
